<?php

namespace app\adminapi\service;

use app\adminapi\model\sysconfig\SysConfigDO;
use app\common\cache\SysConfigCache;
use app\common\exception\OtherException;

class SysConfigService
{

    public function list(array $param)
    {
        $where = [];
        if (isset($param['configName'])) {
            $where[] = ['config_name', 'like', '%' . $param['configName'] . '%'];
        }
        if (isset($param['configKey'])) {
            $where[] = ['config_key', 'like', '%' . $param['configKey'] . '%'];
        }
        $paginate['list_rows'] = $param['pageSize'];
        if (isset($param['pageNo'])) {
            $paginate['page'] = $param['pageNo'];
        }
        $result = (new SysConfigDO())
            ->where($where)
            ->paginate($paginate)
            ->toArray();
        return [
            'total' => $result['total'],
            'list' => $result['data']
        ];
    }

    public function listByConfigKey(array $configKey)
    {
        return (new SysConfigDO())->whereIn('config_key', implode(',', $configKey))->select()->toArray();
    }

    public function addSysConfig(array $sysConfigDO)
    {
        $this->validSysConfigKeyExist($sysConfigDO['configKey'], null);
        $insert = SysConfigDO::create($sysConfigDO);
        $this->refreshCache();
        return $insert;
    }

    public function deleteSysConfig(int $id)
    {
        $this->validSysConfigExist($id);
        $delete = SysConfigDO::destroy($id);
        $this->refreshCache();
        return $delete;
    }

    public function updateSysConfig(array $sysConfigDO)
    {
        $this->validSysConfigExist($sysConfigDO['id']);
        $this->validSysConfigKeyExist($sysConfigDO['configKey'], $sysConfigDO);
        $update = SysConfigDO::update($sysConfigDO);
        $this->refreshCache();
        return $update;
    }

    public function getSysConfig(int $id)
    {
        $this->validSysConfigExist($id);
        return SysConfigDO::find($id);
    }

    public function refreshCache()
    {
        $list = (new SysConfigDO())->select()->toArray();
        (new SysConfigCache())->setSysConfig($list);
    }

    private function validSysConfigKeyExist(string $configKey, $oldInfo)
    {
        $where[] = ['config_key', '=', $configKey];
        if ($oldInfo !== null) {
            $where[] = ['id', '<>', $oldInfo['id']];
        }
        $exist = (new SysConfigDO())->where($where)->find();
        if ($exist) {
            throw new OtherException('配置项已存在');
        }
    }

    private function validSysConfigExist(int $id)
    {
        $exist = SysConfigDO::find($id);
        if (!$exist) {
            throw new OtherException('配置不存在');
        }
    }
}